package com.wheat.vipcard.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Transaction;

import com.opensymphony.xwork2.ActionSupport;
import com.wheat.vipcard.bean.Userinfo;
import com.wheat.vipcard.bean.UserinfoDAO;
import com.wheat.vipcard.utils.PageResultSet;
import com.wheat.vipcard.utils.PageUtil;

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;

	private Userinfo userinfo;

	// 返回的消息
	private String result;

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public Userinfo getUserinfo() {
		return userinfo;
	}

	public void setUserinfo(Userinfo userinfo) {
		this.userinfo = userinfo;
	}

	/**
	 * ��ӵ���
	 * 
	 * @return
	 * @throws Exception
	 */
	public String saveUser() throws Exception {
		Transaction tr = null;
		System.out.println("name =" + userinfo);
		try {
			if (userinfo != null) {
				UserinfoDAO dao = new UserinfoDAO();
				tr = dao.getSession().beginTransaction();
				dao.save(userinfo);
				tr.commit();
				dao.getSession().close();
			}
		} catch (Exception e) {
			tr.rollback();
			e.printStackTrace();
		}
		return "saveUser";
	}

	/**
	 * 分页查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public String listUserByPage() throws Exception {
		request = ServletActionContext.getRequest();
		try {
			UserinfoDAO userinfoDAO = new UserinfoDAO();
			int pageNo = Integer.valueOf(request.getParameter("page").intern());
			PageResultSet<Userinfo> pageResultSetList = userinfoDAO.findUserByPage(userinfo, pageNo,
					new PageUtil().getPageSize());
			Map<String, Object> resultJsonMap = new HashMap<String, Object>();
			resultJsonMap.put("event", pageResultSetList.getList());
			resultJsonMap.put("pageBean", pageResultSetList.getPage());
			resultJsonMap.put("pageCount", pageResultSetList.getPage().getTotalPage());
			this.result = JSONObject.fromObject(resultJsonMap).toString();
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ERROR;
	}

}
